<template>
  <div class="article">
    <a-alert
      style="margin: 10px 0"
      message="温馨提醒"
      description="本服务所有数据均保存在本地,请放心使用！"
      type="warning"
      show-icon
    />
    <a-spin :spinning="loading">
      <a-empty v-if="article == false" :image="simpleImage" />
      <a-form
        v-else
        ref="ruleForm"
        :model="article"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        @submit="handleSubmit"
      >
        <a-form-item label="标题" name="title">
          <a-input v-model:value="article.title" placeholder="文章标题" />
        </a-form-item>
        <a-form-item label="分类" name="category">
            <a-select
                v-model:value="article.category"
                mode="tags"
                style="width: 100%"
                placeholder="文章分类"
            >
                <a-select-option v-for="item in getCategorys" :value="item" :key="item">
                {{ item }}
                </a-select-option>
            </a-select>
          <!-- <a-input v-model:value="article.category" placeholder="文章分类" /> -->
        </a-form-item>
        <a-form-item label="标签" name="tags">
            <a-select
                v-model:value="article.tags"
                mode="tags"
                style="width: 100%"
                placeholder="文章标签"
            >
                <a-select-option v-for="item in getTags" :value="item" :key="item">
                {{ item }}
                </a-select-option>
            </a-select>
          <!-- <a-input v-model:value="article.tags" placeholder="文章标签" /> -->
        </a-form-item>
        <a-form-item label="图床">
          <a-select
            v-model:value="craphBed"
            mode="default"
            style="width: 48%; margin-right: 4%"
            placeholder="选择图床"
          >
            <a-select-option v-for="item in imgService" :key="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-button style="width: 48%" html-type="submit" @click="save">
            {{ $route.name == "Update" ? "更新文章" : "保存文章" }}
          </a-button>
        </a-form-item>
        <a-form-item label="内容" name="content">
          <v-md-editor
            v-model="article.content"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
            height="400px"
          ></v-md-editor>
        </a-form-item>
      </a-form>
    </a-spin>
  </div>
</template>

<script>
// @ is an alias to /src
import { CloseCircleTwoTone } from "@ant-design/icons-vue";
import { Empty } from "ant-design-vue";
export default {
  name: "ArticleAdd",
  components: {},
  data() {
    return {
      loading: false,
      craphBed: "toutiao",
      empty: false,
      labelCol: { span: 2 },
      wrapperCol: { span: 21 },
      imgService: [
        {
          name: "头条",
          value: "toutiao",
        },
        {
          name: "百度",
          value: "baidu",
        },
        {
          name: "哔哩哔哩",
          value: "bilibili",
        },
        {
          name: "新浪",
          value: "sina",
        },
        {
          name: "搜狐",
          value: "souhu",
        },
        {
          name: "腾讯",
          value: "tencent",
        },
        {
          name: "网易",
          value: "wangyi",
        },
        {
          name: "悟空",
          value: "wukong",
        },
        {
          name: "小米",
          value: "xiaomi",
        },
        {
          name: "中关村",
          value: "zol",
        },
      ],
      article: {
        title: "",
        content: "",
        tags: [],
        category: [],
      },
      rules: {
        title: { required: true, message: "文章标题不能为空", trigger: "blur" },
        content: {
          required: true,
          message: "文章内容不能为空",
          trigger: "blur",
        },
        tags: [{
            type: 'array',
            required: true,
            message: '文章标签不能为空',
            trigger: 'change',
          },{type: 'array', min: 1, max: 3, message: '文章标签不能超过3个', trigger: 'blur' }],
        category:[{
            type: 'array',
            required: true,
            message: '文章分类不能为空',
            trigger: 'change',
          },{type: 'array', min: 1, max: 1, message: '文章分类不能超过1个', trigger: 'blur' }],
      },
    };
  },
  computed:{
    // 获取所有标签
      getTags(){
          console.log('执行了1111')
          return this.$store.getters.getTags
      },
      // 获取所有分类
      getCategorys(){
          console.log('执行了')
           return this.$store.getters.getCategorys
      }
  },
  methods: {
    handleSubmit(e) {
      console.log(e);
    },
    save() {
      this.$refs.ruleForm
        .validate()
        .then(() => {
          console.log("values", this.$route.name);
          if (this.$route.name == "Update") {
            this.$store.commit("updateArticle", this.article);
            this.$message.success("文章更新成功");
          } else {
            this.$store.commit("setArticle", this.article);
            this.$message.success("文章保存成功");
          }
          this.$router.push("/article/list");
        })
        .catch((error) => {
          console.log(error);
          this.$notification.error({
            message: "保存失败",
            description: `请把文章内容填写完整`,
            icon: <CloseCircleTwoTone style="color: #f56c6c" />,
          });
        });
    },
    // 图片上传
    handleUploadImage(event, insertImage, files) {
      // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
      console.log(files);
      // 此处只做示例
      let param = new FormData(); // 创建form对象
      param.append("file", files[0]); // 通过append向form对象添加数据
      param.append("chunk", "0"); // 添加form表单中其他数据
      console.log(param.get("file")); // FormData私有类对象，访问不到，可以通过get判断值是否传进去

      this.axios
        .post(`/imgs/upload/${this.craphBed}.php`, param)
        .then((response) => {
          console.log(response.data);
          if (response.data.code == "200") {
            insertImage({
              url: response.data.path,
              desc: files[0].name,
            });
          } else {
            this.$notification.error({
              message: "图片上传失败",
              description: `${response.data.msg}`,
              icon: <CloseCircleTwoTone style="color: #f56c6c" />,
            });
          }
        });
    },
  },
  created() {
    console.log(new Date("yyyy hh:mm:ss").toString);
    if (this.$route.params.id > 0) {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
      }, 400);
      this.article = this.$store.getters.getArticle(this.$route.params.id);
      console.log(this.$store.getters.getArticle(this.$route.params.id));
    }
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
};
</script>
